// pages/rightsMgt/index.js
import Common from '../../common/common.js';
let common = new Common;
const app = getApp();
Page({ 
  data: {
    authOpe: false,
    //搜索用-关键字
    keyValue: "",
    //选中的权限标签页
    uuid: '',
    //店主和店长
    managerList: [],
    //权限列表
    authList: [],
    //员工列表
    userListAll: [],
    //上拉加载控制
    scrollHeight: 0,
    isLoading: false,
    hasData: true,
    pageNum: 1,
    pageSize: 100,
    //是否已全选
    checkedAll: false,
    userType: '',
    loadingShow: true,
  },
  // 详情
  toDetil: function(e) {
    let userId = e.currentTarget.dataset.id;
    let orgSeq = e.currentTarget.dataset.org;
    let userType = e.currentTarget.dataset.usertype;
    // let authoritylist = e.currentTarget.dataset.authoritylist;
    // let aut;
    // if (authoritylist){
    //   authoritylist.filter(item => {
    //     if (item.authorityName == '卡券发放'){
    //       aut = 0
    //     } 
    //   })
    // }
    // console.log(aut)
    // return;
    wx.navigateTo({
      url: '/pages/rightsMgt/rootEmployees/rootEmployees?orgSeq=' + orgSeq + '&userId=' + userId + "&userType=" + userType
    })
    return
    let routeUrl = '';
    let routeType = 'navigateTo';
    let params = '';
    common.routeLink(routeUrl, params, routeType)
  },
  /**
   * 搜索控制
   */
  inputTyping: function(e) {
    this.setData({
      keyValue: e.detail.value
    });
    // this.resetDatas();
    this.getUserList();
  },
  /**
   * 点击权限标签页
   */
  switchAuth: function(e) {
    var that = this;
    console.log(e, typeof(e), typeof e === 'string', typeof(e) === 'string');
    //设置当前选中的权限ID
    var uuid = "";
    if (typeof(e) === 'string') {
      uuid = e;
    } else {
      uuid = e.currentTarget.dataset.uuid;
    }
    this.setData({
      uuid: uuid
    })
    //勾选有该权限的员工
    var that = this;
    var userListAll = that.data.userListAll;
    console.log(that.data.userListAll)
    for (var i = 0; i < userListAll.length; i++) {
      var authorityList = userListAll[i].authorityList;
      var hasMatch = false;
      for (var j = 0; j < authorityList.length; j++) {
        if (uuid == authorityList[j].uuid) {
          userListAll[i].checked = true;
          hasMatch = true;
          break;
        }
      }
      if (!hasMatch) {
        userListAll[i].checked = false;
      }
    }
    that.setData({
      userListAll: userListAll
    })
  },
  /**
   * 查询店长和店主
   */
  getManagerList: function() {
    var data = {
      "orgSeq": getApp().globalData.orgSeq
    };
    common.requestAjax('/api/user-service/v1/user/queryManage', 'POST', data).then(res => {
      if (res.data.code == 1) {
        let managerList = res.data.records;
        let shopOwner = [];//店主数组
        let shopManager = []//店长数组
        for (var i = 0; i < managerList.length;i++){
          // 店主拼成数组
          if (managerList[i].userType ==4){
            shopOwner.push(managerList[i])
          }else{
            // 店长拼成数组
            shopManager.push(managerList[i])
          }
        }
        managerList = shopOwner.concat(shopManager)
        console.log(managerList)
        this.setData({
          managerList: managerList
        })
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      common.showToast(err);
    })
  },
  /**
   * 查询权限列表
   */
  getAuthList: function() {
    var data = {
      "orgSeq": getApp().globalData.orgSeq
    };
    common.requestAjax('/api/user-service/v1/detail/queryAuthority', 'POST', data).then(res => {
      if (res.data.code == 1) {   
        this.setData({
          loadingShow: false,
          authList: res.data.records
        })
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      console.log(err);
    })
  },
  /**
   * 查询用户列表
   */
  getUserList: function() {
    var that = this;
    var data = {
      "orgSeq": getApp().globalData.orgSeq,
      "keyWords": that.data.keyValue
    };
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    common.requestAjax('/api/user-service/v1/user/queryStorePerson', 'POST', data).then(res => {
      // wx.hideLoading();
      if (res.data.code == 1) {
        var userList = res.data.records;
        this.setData({
          userListAll: res.data.records
        })
        console.log(this.data.userListAll)
        // var userListAll = that.data.userListAll;
        // userListAll = userListAll.concat(userList);
        // that.setData({
        //   userListAll: userListAll
        // })
        //勾选有该权限的员工
        if (that.data.uuid != '') {
          that.switchAuth(that.data.uuid);
        }
      } else {
        common.showToast(res.data.message);
      }
      //上拉加载控制
      // if (res.data.records == null || res.data.records.length == 0) {
      //   that.errorDatas();
      // } else {
      //   that.successDatas();
      // }
    }).catch(err => {
      // wx.hideLoading();
      that.errorDatas();
      console.log(err);
    })
  },
  /**
   * 上拉加载重置数据
   */
  resetDatas: function() {
    //标识设置加载完成，页数+1，数据清空
    this.setData({
      isLoading: false,
      pageNum: 1,
      userListAll: []
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
  },
  /**
   * 上拉加载成功处理
   */
  successDatas: function() {
    var that = this;
    //标识设置加载完成，页数+1
    that.setData({
      isLoading: false,
      pageNum: that.data.pageNum + 1
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    //隐藏暂无数据
    that.setData({
      hasData: true
    })
  },
  /**
   * 上拉加载失败处理
   */
  errorDatas: function() {
    var that = this;
    //标识设置加载完成
    that.setData({
      isLoading: false
    })
    //隐藏导航栏loading
    wx.hideNavigationBarLoading();
    //显示暂无数据
    if (that.data.pageNum == 1) {
      that.setData({
        hasData: false
      })
    }
  },
  /**
   * 上拉加载事件
   */
  scrollTolower(e) {
    var that = this;
    //正在加载中阻止再次查询
    if (that.data.isLoading) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    that.setData({
      isLoading: true
    })
    //获取数据
    that.getUserList();
  },
  /**
   * 选择员工
   */
  checkboxChange: function(e) {
    var userId = e.currentTarget.dataset.userid;
    var valueArray = e.detail.value;
    var checked = false;
    if (valueArray[0] == userId) {
      //每个员工一个checkboxgroup，如果data-goodsid值和checkbox返回的值相等，表示选中商品
      checked = true;
    }
    var userListAll = this.data.userListAll;
    for (var i = 0; i < userListAll.length; i++) {
      if (userListAll[i].userId == userId) {
        userListAll[i].checked = checked;
        break;
      }
    }
    this.setData({
      userListAll: userListAll
    })
  },
  /**
   * 全选
   */
  checkboxChangeAll: function(e) {
    var checked = e.currentTarget.dataset.checkedall;
    checked = !Boolean(checked);
    var userListAll = this.data.userListAll;
    for (var i = 0; i < userListAll.length; i++) {
      userListAll[i].checked = checked;
    }
    this.setData({
      userListAll: userListAll,
      checkedAll: checked
    })
  },
  /**
   * 获取已选择的员工列表
   */
  getChoosedUser: function() {
    var that = this;
    var data = [];
    var userListAll = that.data.userListAll;
    for (var j = 0; j < userListAll.length; j++) {
      var checked = userListAll[j].checked;
      if (checked) {
        data.push(
          userListAll[j].userId
        )
      }
    }
    return data;
  },
  /**
   * 设置权限
   */
  setAuth: function() {
    var userListAll = this.data.userListAll;
    var authList = this.data.authList;
    console.log(userListAll+'====================')
    console.log(authList + '-------------------------')
    if (userListAll.length == 0) {
      common.showToast("该店铺暂时没有员工");
      return;
    }
    if (authList.length == 0) {
      common.showToast("权限列表为空");
      return;
    }
    //点击第一个权限
    this.switchAuth(authList[0].uuid);
    this.setData({
      authOpe: true
    })
  },
  /**
   * 保存权限
   */
  saveAuth: function() {
    var that = this;
    var data = that.getChoosedUser();
    console.log(data);
    // if (data.length == 0) {
    //   common.showToast("清选择员工");
    //   return;
    // }
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    wx.showModal({
      title: '提示',
      content: '您确定要执行此操作吗',
      success: function(res) {
        if (res.cancel) {　　　　　　　　 //点击取消,默认隐藏弹框

          　　　　　　} else {　　　　　　　　 //点击确定
          var dataWrap = {};
          dataWrap.orgSeq = getApp().globalData.orgSeq;
          dataWrap.authorityId = that.data.uuid;
          dataWrap.userList = data;
          common.requestAjax('/api/user-service/v1/detail/saveAuthority', 'POST', dataWrap).then(res => {
            wx.hideLoading();
            if (res.data.code == 1) {
              common.showToast(res.data.message);
              that.resetDatas();
              that.getUserList();
            } else {
              common.showToast(res.data.message);
            }
          }).catch(err => {
            wx.hideLoading();
            common.showToast("系统异常，请稍后重试！");
          })　　　　　
        }
      }
    })


  },
  /**
   * 取消权限
   */
  cancleAuth: function() {
    this.setData({
      authOpe: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let userType = app.globalData.shopInfo.userType;
    this.setData({
      userType: userType
    });
    console.log(this.data.userType)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // getApp().globalData.orgSeq = "2e8f4c46-ee3b-4b4b-9270-cf00c28271af";
    //获取店长和店主
    this.getManagerList();
    //获取权限列表
    this.getAuthList();
    //获取用户列表
    // this.getUserList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    //检测登陆状态
    // let loginStatus = wx.getStorageSync('loginStatus');
    // if (loginStatus == 0) {
    //   console.log('去登陆')
    //   //去授权登陆
    //   wx.navigateTo({
    //     url: '/pages/login/index',
    //   })x
    // } else {

    // }
    // getApp().globalData.orgSeq = "2e8f4c46-ee3b-4b4b-9270-cf00c28271af";
    //获取店长和店主
    this.getManagerList();
    //获取权限列表
    this.getAuthList();
    //获取用户列表
    this.getUserList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
  // 监听页面上滑
  onReachBottom: function () {
    var that = this;
    let page = that.data.pageNum;
    page = page + 1
    that.setData({
      pageNum: page
    })
    // that.resetDatas();
    that.getUserList();
    // that.getManagerList();
    // that.getAuthList();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    //正在加载中阻止再次查询
    if (that.data.isLoading) {
      return;
    }
    //显示导航栏loading
    wx.showNavigationBarLoading();
    //设置标识加载中
    that.setData({
      isLoading: true
    })
    //获取数据
    that.resetDatas();
    that.getUserList();
    that.getManagerList();
    that.getAuthList();
    setTimeout(function() {
      wx.stopPullDownRefresh();
    }, 10)
  },
})